package com.example.wallet.utils

import android.os.Environment
import android.util.Log
import com.example.wallet.global.AppGlobals
import java.io.File

const val WALLET_ROOT_FILE = "/sst_root_file_dir"

const val WALLET_CHILD_FILE = "/sst_wallet_child_file"

val SD_CARD_DIR = Environment.getExternalStorageDirectory().absolutePath

fun walletRootFileDirs(): File {
    val rootFile = File(SD_CARD_DIR, WALLET_ROOT_FILE)
    if (!rootFile.exists()) {
        rootFile.mkdirs()
    }
    return rootFile
}

fun getWalletChildFile(mAccountFileName: String):String{
    val childFile = File(
        walletRootFileDirs(),
        "/${WALLET_CHILD_FILE}"
    )
     if (!childFile.exists()){
         return ""
     }

   val file=File(childFile, mAccountFileName)

    if (!file.exists()){
        return ""
    }
    return file.absolutePath
}

fun createWalletChildFile(): File {
    val walletRootFileDirs = walletRootFileDirs()
    Log.d("createCount", "walletRootFileDirs.exists(): ${walletRootFileDirs.exists()}")
    val childFile = File(
        walletRootFileDirs,
        "/${WALLET_CHILD_FILE}"
    )
    if (!childFile.exists()) {
        childFile.mkdirs()
    }
    return childFile
}

fun haveCreatedWallet(): Boolean {
    return walletChildFileCount(null) > 0
}

fun walletChildFileCount(rootFile: File?): Int {

    var mCount = 0

    val walletRootFileDirs = rootFile ?: walletRootFileDirs()

    if (walletRootFileDirs.isDirectory) {

        walletRootFileDirs.listFiles()?.forEach {
            val fileName = it.name
            if (it.isFile
                && fileName.isNotEmpty()
                && fileName.startsWith(WALLET_CHILD_FILE)
            ) {
                mCount++
            } else if (it.isDirectory) {
                mCount += walletChildFileCount(it)
            }
        }
    }
    return mCount
}

